package com.view;

import java.util.List;

import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;

import com.control.MyTreeControl;
import com.model.Node;
import com.model.Tree;

public class MyJTree extends JTree {

	private static final long serialVersionUID = 1L;

	protected DefaultMutableTreeNode root;

	public MyJTree(MyTreeControl<String> atree) {
		super();
		creatTree(atree);
		DefaultTreeModel model = new DefaultTreeModel(root);
		this.setExpandedState(new TreePath(this.root), true);
		this.setModel(model);
		this.setExpandsSelectedPaths(true);
		this.setExpandsSelectedPaths(true);
	}

	@SuppressWarnings({ "unchecked", "unused" })
	private void creatTree(MyTreeControl<String> atree) {
		@SuppressWarnings("rawtypes")
		Tree tree = atree.getTree();
		List<Node<String>> lists = tree.getNodes();
		Object[] object = lists.toArray();
		root = new DefaultMutableTreeNode(((Node<String>) object[0]).getData());
		setTree(root, ((Node<String>) object[0]).getChildNodes());
	}

	private void setTree(DefaultMutableTreeNode node, List<Node<String>> children) {
		if (children.size() > 0) {
			for (Node<String> n : children) {
				if (n.getType()==0) {
					DefaultMutableTreeNode dian = new DefaultMutableTreeNode(n.getData().toString());
					node.add(dian);
					if (n.getChildNodes().size() > 0)
						setTree(dian, n.getChildNodes());
				}
			}
		}
	}

}
